use std::fmt::Display;

// 生命周期标注的正反案例
struct Animal<'a> {
    name: &'a str,
    keeper: &'a str
}

// 正确的特质约束
trait Feed {
    fn feed(&self) -> String;
}

struct Panda<'a> {
    data: Animal<'a>
}

impl<'a> Feed for Panda<'a> {
    fn feed(&self) -> String {
        format!("{}正在喂食{}", self.data.keeper, self.data.name)
    }
}

fn main() {
    // 正确生命周期案例
    let keeper1 = "张饲养员";
    let lingling = Panda {
        data: Animal {
            name: "玲玲",
            keeper: keeper1
        }
    };
    println!("{}", lingling.feed()); // 正常输出

    危险的生命周期案例（注释掉的错误代码）
    let trouble;
    {
        let keeper2 = String::from("临时工");
        trouble = Panda {
            data: Animal {
                name: "麻烦",
                keeper: keeper2
            }
        };
    } // keeper2在此死亡
    println!("{}", trouble.feed()); // 试图使用已死引用
}
